package com.EM1.www.dao;
import com.EM1.www.po.Teacher;
import com.EM1.www.util.Connectmysql;

import java.sql.*;
import java.util.ArrayList;

public class ConnectTeacher {
    public Teacher selectTeacher(int userId) throws Exception {
        Connection conn = Connectmysql.Connectmysql();
        String sql="select * from teacher where user_id=?";
        PreparedStatement pmt= conn.prepareStatement(sql);
        pmt.setInt(1,userId);
        ResultSet res = pmt.executeQuery();
        Teacher teacher=null;
        String sql1="select * from grade where user_id=?";
        PreparedStatement pmt1 = conn.prepareStatement(sql1);
        pmt1.setInt(1,userId);
        ResultSet res1 = pmt1.executeQuery();
        ArrayList<Integer> grades=new ArrayList<>();
        while (res1.next()){
            int grade = res1.getInt("grade");
            grades.add(grade);
        }
        while (res.next()) {
            teacher = new Teacher(res.getString("subject"), grades, res.getString("intruduction"));
            teacher.setId(userId);
            teacher.setName(res.getString("username"));
        }

        pmt.close();
        pmt1.close();
        conn.close();
        return teacher;
    }
    public void changeMsg(String username,String subject,String instruduction,int userId) throws Exception {
        Connection conn = Connectmysql.Connectmysql();
        String sql="update teacher set subject=?,intruduction=?,username=?where user_id=?";
        String usesql="update user set username=?where id=?";
        PreparedStatement pmt = conn.prepareStatement(sql);
        PreparedStatement userpmt = conn.prepareStatement(usesql);
        pmt.setString(1,subject);
        pmt.setString(2,instruduction);
        pmt.setString(3,username);
        pmt.setInt(4,userId);
        pmt.executeUpdate();
        userpmt.setString(1,username);
        userpmt.setInt(2,userId);
        userpmt.executeUpdate();
        userpmt.close();
        conn.close();
        pmt.close();
    }
    public void SetTeacher(String username,int id) throws Exception {
        Connection conn = Connectmysql.Connectmysql();
        String sql="insert into teacher (username,user_id) values (?,?)";
        PreparedStatement pmt = conn.prepareStatement(sql);
        pmt.setString(1,username);
        pmt.setInt(2,id);
        pmt.executeUpdate();
        conn.close();
        pmt.close();
    }
}
